﻿namespace EnterpriseLibrary.Caching.AzureBackingStore
{
    using System.Collections.Generic;

    using Microsoft.ApplicationServer.Caching;

    public class AzureDataCacheHelper
    {
        #region Properties

        /// <summary>
        /// Gets the data cache factory.
        /// </summary>
        public DataCacheFactory DataCacheFactory
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the data cache list.
        /// </summary>
        public Dictionary<string, DataCache> DataCacheList
        {
            get;
            private set;
        }

        #endregion Properties

        #region Methods

        /// <summary>
        /// Gets the data cache.
        /// </summary>
        /// <param name="cacheName">Name of the cache.</param>
        /// <returns>The data cache</returns>
        public DataCache GetDataCache(string cacheName)
        {
            DataCache dataCache;
            if (this.DataCacheList.ContainsKey(cacheName))
            {
                dataCache = this.DataCacheList[cacheName];
            }
            else
            {
                if (this.DataCacheFactory == null)
                {
                    this.Initilize();
                }

                dataCache = this.DataCacheFactory.GetCache(cacheName);

                this.DataCacheList.Add(cacheName, dataCache);
            }

            return dataCache;
        }

        /// <summary>
        /// Gets the data cache
        /// </summary>
        /// <param name="cacheName">Name of the cache cluster</param>
        /// <param name="region">Name of the region</param>
        /// <returns>The data cache</returns>
        public DataCache GetDataCache(string cacheName, string region)
        {
            DataCache dataCache;
            if (this.DataCacheList.ContainsKey(cacheName))
            {
                dataCache = this.DataCacheList[cacheName];
            }
            else
            {
                if (this.DataCacheFactory == null)
                {
                    this.Initilize();
                }

                dataCache = this.DataCacheFactory.GetCache(cacheName);

                dataCache.CreateRegion(region);
                this.DataCacheList.Add(cacheName, dataCache);
            }

            return dataCache;
        }

        /// <summary>
        /// Initilizes this instance.
        /// </summary>
        public void Initilize()
        {
            this.DataCacheFactory = new DataCacheFactory();
            this.DataCacheList = new Dictionary<string, DataCache>();
        }

        #endregion Methods
    }
}